
// 检测全局命名空间是否存在
const __Global__ = window ?? globalThis;
if(!Reflect.has(__Global__, 'mtec')){
	Reflect.set(__Global__, 'mtec', {});
	Reflect.set(mtec, '__mtec__', 'Many technologies');
}

mtec.getype = function(value){
	let type = typeof value;
	return type=='object' ? value==null ? 'null' : Array.isArray(value) ? 'array' : 'object' : type;
}

mtec.same = function(a, b, record){
	if(a===b) return true;

	let [ta, tb] = [a, b].map(_=>mtec.getype(_));

	if(ta!=tb) return [ta, tb].every(t=>['number', 'bigint'].includes(t)) ? a==b : false;

	if(!['array', 'object'].includes(ta)) return a==b;

	if(!record) record = {cache: [], mark: new Map(), list: []};

	let token = [a, b].map(v=>{
		if(record.mark.has(v)) return record.mark.get(v);

		let mark = mtec.string.randomToken(3, 36, _t=>!record.list.includes(_t));
		record.list.push(mark);
		record.mark.set(v, mark);
		return mark;
	}).sort().join('::');

	if(record.cache.includes(token)) return true;
	record.cache.push(token);

	let [key_a, key_b] = [a, b].map(v=>Reflect.ownKeys(v).filter(k=>v[k]!=undefined && v[k]!=null).sort());

	if(key_a.length==key_b.length && key_a.every((k, i)=>k==key_b[i])) return key_a.every(k=>mtec.same(a[k], b[k], record));

	return false;
}

mtec.pickValueByType = function<T extends [mtec.type_string, any][]>(values: any[], types: T){
	let map = values.reduce((m, v)=>{
		let t = mtec.getype(v);
		if(m[t]==undefined) m[t] = [];

		Array.prototype.unshift.call(m[t], v);
		return m;
	}, {});

	return types.map(picker=>{
		let v = Reflect.get(map, picker[0]);
		return v ? v.length>1 ? Array.prototype.pop.call(v) : v[0] : picker[1];
	}) as mtec.TypeArray<mtec.PickFirst<T>>;
}

mtec.delay = function(delay, call, ...args){
	return new Promise((s, j)=>{
		let id = setTimeout((c, a)=>{
			clearTimeout(id);
			s(typeof c=='function' ? c(...a) : c);
		}, delay * 1000, call, args)
	});
}

mtec.drawLots = function(bucket){
	if(bucket.length<=0) return void 0;
	if(bucket.length==1) return bucket[0][0];

	let data_list = [];
	let weight_list = [];
	let total = 0;

	for(let [data, weight] of bucket){
		let v = Number(weight);
		if(!(v > 0)) continue;

		total += v;
		data_list.push(data);
		weight_list.push(total);
	}

	let point = Math.random() * total;
	let i = 0;
	while(point >= weight_list[i]) i++;

	return data_list[i];
}

mtec.fusionData = function(target, ...list){
	if(target instanceof Object){
		if(Array.isArray(target)){
			//@ts-ignore
			list.forEach(data=>Array.isArray(data) ? target.push(...data) : target.push(data));
		}else if(!(target instanceof Function)){
			let ls = list.filter(data=>data instanceof Object && !(data instanceof Function));
			let map = ls.reduce((m, data, i)=>{
				Reflect.ownKeys(data).forEach(key=>m.set(key, i));
				return m;
			}, new Map());
			//@ts-ignore
			map.forEach((i, key)=>Reflect.set(target, key, Reflect.get(ls[i], key)));
		}
	}else{
		if(typeof target == 'bigint'){
			list.forEach(data=>{
				switch(typeof data){
					//@ts-ignore
					case 'boolean': data = Number(data); case 'object': case 'undefined': data = BigInt(0); case 'number': if(isNaN(data)) data = 0; data = BigInt(data); break;
					//@ts-ignore
					case 'symbol': data = String(data); break;
				}
				// @ts-ignore
				target += data;
			})
		}else if(['string', 'symbol'].includes(typeof target)){
			//@ts-ignore
			target = String(target);
			//@ts-ignore
			list.forEach(data=>target += (typeof data=='symbol' ? String(data) : data));
		}else{
			list.forEach(data=>{
				switch(typeof data){
					//@ts-ignore
					case 'bigint': target = Number(target); if(isNaN(target)) target = BigInt(0); break;
					//@ts-ignore
					case 'symbol': data = String(data);
				}
				//@ts-ignore
				target += data;
			})
		}
	}

	return target as any;
}

mtec.cloneData = function(data, record){
	let t = mtec.getype(data);

	if(['string', 'number', 'boolean', 'bigint', 'undefined', 'null'].includes(t)) return data;
	else if(t == 'function') return Function.prototype.bind.call(data, null);
	else if(t == 'symbol') return Symbol(data['description']);
	else{
		if(!record) record = new Map();

		if(record.has(data)) return record.get(data);

		let target;
		if(t=='array') target = [];
		else target = {};

		record.set(data, target);

		//@ts-ignore
		if(t=='array') data.forEach(el=>target.push(mtec.cloneData(el)));
		else{
			//@ts-ignore
			Reflect.ownKeys(data).forEach(key=>Reflect.set(target, key, Reflect.get(data, key)));
			//@ts-ignore
			Reflect.setPrototypeOf(target, Reflect.getPrototypeOf(data));
		}

		return target;
	}
}

mtec.CountAverage = class implements mtec.CountAverage{
	private count = 0;
	private _average: number;

	constructor(init?: number){
		if(init) this.add(init);
	}

	public get average(){
		return this._average ?? 0;
	}

	public add(value: number){
		this.count++;
		this._average = this.average + (value - this.average) / this.count;
		return this._average;
	}

	public clean(){
		this.count = 0;
		this._average = 0;
	}
}

mtec.NudityPromise = class<V> implements mtec.NudityPromise<V>{
	private inited: boolean;
	private status: 'waiting'|'resolve'|'reject';
	private result: any;
	private _resolve_call_: (value: V | PromiseLike<V>)=>void;
	private _reject_call_: (reason: any)=>void;

	public promise: Promise<V>;

	constructor(){
		this.inited = false;
		this.status = 'waiting';
		this.promise = new Promise((s, j)=>{
			this._resolve_call_ = s;
			this._reject_call_ = j;
			this.inited = true;
			this.reply();
		});
	}

	public resolve(value: V | PromiseLike<V>){
		this.re_call('resolve', value);
	}

	public reject(reason: any){
		this.re_call('reject', reason);
	}

	private re_call(status: 'resolve'|'reject', result: any){
		if(this.status=='waiting'){
			[this.status, this.result] = [status, result];
			this.reply();
		}
	}

	private reply(){
		if(this.inited && this.status!='waiting'){
			switch(this.status){
				case 'resolve': this._resolve_call_(this.result); break;
				case 'reject': this._reject_call_(this.result); break;
			}
		}
	}
}

mtec.JsonString = function(data){
	let tp = typeof data;
	if(tp != 'object') return JSON.stringify(data);
	if(data == null) return 'null';

	let copy_map: Map<any, any> = new Map();
	let token_map: Map<any, string> = new Map();
	let token_cache = [];

	let data_list = [data];
	copy_map.set(data, Array.isArray(data) ? [] : {});
	token_map.set(data, mtec.string.randomToken(5, 36, tlkn=>!token_cache.includes(tlkn)));

	for(let i = 0; i < data_list.length; i++){
		let item = data_list[i];
		let copy = copy_map.get(item);
		let key_list: Array<string|number|symbol> = Array.isArray(item) ? mtec.array.create(item.length, i=>i) : Reflect.ownKeys(item);
		let data_flag: Array<[string, string|number|symbol]> = [];

		for(let key of key_list){
			let value = Reflect.get(item, key);

			if(typeof value != 'object') Reflect.set(copy, key, value);
			else if(value == null) Reflect.set(copy, key, null);
			else if(token_map.has(value)) Reflect.set(copy, key, '<-[ref]->'+token_map.get(value));
			else{
				let token = mtec.string.randomToken(5, 36, t=>!token_cache.includes(t));
				let cp = Array.isArray(value) ? [] : {};
				token_map.set(value, token);
				copy_map.set(value, cp);
				data_list.push(value);
				if(Array.isArray(item)){
					Reflect.set(copy, key, cp);
					data_flag.push([token, key]);
				}else Reflect.set(copy, token+'<-[data]->'+String(key), cp);
			}
		}

		if(data_flag.length>0 && Array.isArray(item)) copy.push(data_flag.map(el=>el[0] + '<-[data]->' + String(el[1])).join(';'));
	}

	return token_map.get(data) + '<-[data]->' + JSON.stringify(copy_map.get(data));
}

mtec.parseJson = function(json_string){
	let token: string;
	let data: any;
	if(json_string.includes('<-[data]->')) [token, json_string] = json_string.replace('<-[data]->', '->[data]<-').split('->[data]<-');

	try{
		data = JSON.parse(json_string);
	}catch(err){
		data = json_string;
	}

	if(typeof data != 'object') return data;

	let data_map: Map<string,any> = new Map();
	data_map.set(token, data);
	let data_list = [data];

	for(let i = 0; i < data_list.length; i++){
		let item = data_list[i];

		if(Array.isArray(item)){
			if(typeof item.lastElement == 'string' && item.lastElement.includes('<-[data]->')){
				(item.pop() as string).split(';').map(item=>{
					let [token, index] = item.split('<-[data]->');
					return [token, Number(index)] as [string, number];
				}).forEach(el=>data_map.set(el[0], item[el[1]]));
			}

			item.forEach((el, i, arr)=>{
				if(typeof el == 'string' && el.includes('<-[ref]->')){
					let token = el.replace('<-[ref]->', '');
					arr[i] = data_map.get(token);
				}else if(typeof el == 'object') data_list.push(el);
			});
		}else if(item != null){
			Reflect.ownKeys(item).forEach(key=>{
				let value = Reflect.get(item, key);

				if(typeof value == 'object') data_list.push(value);
				else if(typeof value == 'string' && value.includes('<-[ref]->')){
					let token = value.replace('<-[ref]->', '');
					value = data_map.get(token);
					Reflect.set(item, key, value);
				}

				if(typeof key == 'string' && key.includes('<-[data]->')){
					Reflect.deleteProperty(item, key);
					let [token, k] = key.split('<-[data]->');
					Reflect.set(item, k, value);
					data_map.set(token, value);
				}
			});
		}
	}

	return data;
}
